package com.zhihao.zhihaopicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.batch.MybatisBatch;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.zhihao.zhihaopicturebackend.api.aliyunai.AliYunAiApi;
import com.zhihao.zhihaopicturebackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.zhihao.zhihaopicturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.zhihao.zhihaopicturebackend.common.DeleteRequest;
import com.zhihao.zhihaopicturebackend.constant.PictureListByPageRedisKeyConstant;
import com.zhihao.zhihaopicturebackend.exception.BusinessException;
import com.zhihao.zhihaopicturebackend.exception.ErrorCode;
import com.zhihao.zhihaopicturebackend.exception.ThrowUtils;
import com.zhihao.zhihaopicturebackend.manager.CosManager;
import com.zhihao.zhihaopicturebackend.manager.FileManager;
import com.zhihao.zhihaopicturebackend.manager.upload.FilePictureUpload;
import com.zhihao.zhihaopicturebackend.manager.upload.PictureUploadTemplate;
import com.zhihao.zhihaopicturebackend.manager.upload.UrlPictureUpload;
import com.zhihao.zhihaopicturebackend.model.dto.file.UploadPictureResult;
import com.zhihao.zhihaopicturebackend.model.dto.picture.*;
import com.zhihao.zhihaopicturebackend.model.entity.ServicePicture;
import com.zhihao.zhihaopicturebackend.model.entity.ServiceSpace;
import com.zhihao.zhihaopicturebackend.model.entity.SystemUser;
import com.zhihao.zhihaopicturebackend.model.enums.PictureReviewStatusEnum;
import com.zhihao.zhihaopicturebackend.model.vo.PictureVO;
import com.zhihao.zhihaopicturebackend.model.vo.UserVO;
import com.zhihao.zhihaopicturebackend.service.ServicePictureService;
import com.zhihao.zhihaopicturebackend.mapper.ServicePictureMapper;
import com.zhihao.zhihaopicturebackend.service.ServiceSpaceService;
import com.zhihao.zhihaopicturebackend.service.SystemUserService;
import com.zhihao.zhihaopicturebackend.utils.ColorSimilarUtils;
import com.zhihao.zhihaopicturebackend.utils.ColorTransformUtils;
import com.zhihao.zhihaopicturebackend.utils.PictureQueryTimesThreadPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.BatchResult;
import org.apache.ibatis.session.SqlSessionFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
* @author Jackson
* @description 针对表【service_picture(图片表)】的数据库操作Service实现
* @createDate 2024-12-23 16:19:52
*/
@Slf4j
@Service
public class ServicePictureServiceImpl extends ServiceImpl<ServicePictureMapper, ServicePicture>
    implements ServicePictureService{

    @Resource
    private FileManager fileManager;

    @Resource
    private CosManager cosManager;

    @Resource
    private SystemUserService userService;

    @Resource
    private FilePictureUpload filePictureUpload;

    @Resource
    private UrlPictureUpload urlPictureUpload;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ServiceSpaceService spaceService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private AliYunAiApi  aliYunAiApi;

    // caffeine
    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(PictureListByPageRedisKeyConstant.MAX_SIZE_CAFFEINE)
                    // 缓存 5 分钟移除
                    .expireAfterWrite(PictureListByPageRedisKeyConstant.EXPIRE_TIME_CAFFEINE, TimeUnit.MINUTES)
                    .build();

    // bing搜索引擎作为爬取目标---q=%s 搜索词占位符
    private final static String SEARCHBYBATCHWEB = "https://cn.bing.com/images/async?q=%s&mmasync=1";

    /*
        相比单独只上传图片接口，已将图片和用户id进行绑定，可用于后续的限制盗刷等
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, SystemUser loginUser) {
        if (inputSource == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片为空");
        }
        // 校验空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            ServiceSpace space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            // 改为使用统一的权限校验
            // 校验是否有空间的权限，仅空间管理员才能上传
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
//            }
            // 校验额度(后置校验)
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }
        }
        // 用于判断是新增还是更新图片
        Long pictureId = null;
        if (pictureUploadRequest != null) {
            pictureId = pictureUploadRequest.getId();
        }
        // 如果是更新图片，需要校验图片是否存在
        if (pictureId != null) {
            ServicePicture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(ObjectUtil.isNull(oldPicture), ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            // 改为使用统一的权限校验
//            // 仅本人或管理员可编辑
//            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//            }
            // 校验空间是否一致
            // 没传 spaceId，则复用原有图片的 spaceId
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                // 传了 spaceId，必须和原有图片一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间 id 不一致");
                }
            }
        }
        // 上传图片，得到信息
        // 按照用户 id 划分目录 => 按照空间id划分目录
        String uploadPathPrefix;
        if (spaceId == null) {
            uploadPathPrefix = String.format("public/%s", loginUser.getId());
        } else {
            uploadPathPrefix = String.format("space/%s", spaceId);
        }
        // 根据 inputSource 类型区分上传方式
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
        // 构造要入库的图片信息  BeanUtil or MapStruct均可
        ServicePicture picture = new ServicePicture();
        // 补充设置 spaceId
        picture.setSpaceId(spaceId);
        // url
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setWebpUrl(uploadPictureResult.getWebpUrl());
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        // 是否自定义图片名称
        String picName = uploadPictureResult.getPicName();
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        // 图片主色调
        picture.setPicColor(ColorTransformUtils.getStandardColor(uploadPictureResult.getPicColor()));
        // cos上传后图片类型和原图类型不一致(eg:jpg->jpeg)
//        String pictureSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());     // 以原图文件为准
//        picture.setPicFormat(pictureSuffix.toUpperCase());
        picture.setPicFormat(uploadPictureResult.getPicFormat());   // 以上传后的cos文件信息后缀为准
        picture.setUserId(loginUser.getId());
        /*
            补充审核信息
         */
        fillReviewParams(picture, loginUser);
        // 如果 pictureId 不为空，表示更新，需要补充id和编辑时间等参数
        if (pictureId != null) {
            // 如果是更新，需要补充 id 和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        // 开启事务
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
            if (finalSpaceId != null) {     // 用户上传私有空间行为
                boolean update = spaceService.lambdaUpdate()
                        .eq(ServiceSpace::getId, finalSpaceId)
                        .setSql("total_size = total_size + " + picture.getPicSize())
                        .setSql("total_count = total_count + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture;
        });
        // TODO:如果是更新图片,，清理原有图片占用的cos资源(同时要不要返还给用户差额空间等)
        return PictureVO.objToVo(picture);
    }

    @Override
    public boolean deletePicture(DeleteRequest deleteRequest, SystemUser loginUser) {
        // 要删除的图片id
        long id = deleteRequest.getId();
        // 判断是否存在
        ServicePicture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限，已经改为使用注解鉴权
//        checkPictureAuth(loginUser, oldPicture);
        // 开启事务
        transactionTemplate.execute(status -> {
            // 提取图片cos对象key     // maybe再提取封装出来一个clearPictureFile()方法
            // 查找主机名的结束位置
            String oldPictureUrl = oldPicture.getUrl();
            int index = oldPictureUrl.indexOf(".com") + 4; // ".com" 结束后的索引
            String deleteObjectKey = oldPictureUrl.substring(index);
            log.info("COS删除对象的key为:{}",deleteObjectKey); // 输出：/public/1870076636240334849/20241223_EvqUQA2EHS.png
            // 操作数据库---先删除数据库好一点maybe 容错高
            boolean result = this.removeById(id);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 删除COS对应对象
            try {
                cosManager.deleteObject(deleteObjectKey);
            }catch (Exception e) {
                log.info("COS对象删除失败",e);
                throw new BusinessException(ErrorCode.OPERATION_ERROR);
            }
            // 释放额度
            Long spaceId = oldPicture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(ServiceSpace::getId, spaceId)
                        .setSql("total_size = total_size + " + oldPicture.getPicSize())
                        .setSql("total_count = total_count + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // todo:异步清理文件
        // todo:这里有可能出现对象存储上的图片文件实际没被清理的情况。但是对于用户来说，不应该感受到 “删了图片空间却没有增加”，所以没有将这一步添加到事务中。可以通过定时任务检测作为补偿措施。
        return true;
    }

    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, SystemUser loginUser) {
        // 在此处将实体类和 DTO 进行转换
        ServicePicture picture = new ServicePicture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 判断是否存在
        ServicePicture oldPicture = getById(pictureEditRequest.getId());
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限---仅本人或管理员可编辑
        // 校验权限，已经改为使用注解鉴权
//        checkPictureAuth(loginUser, oldPicture);
        // 补充审核信息
        fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }


    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, SystemUser loginUser) {
        // all get
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        // 请求中的审核状态正常应该就是 pass/reject,所以当遇到传过来的审核状态还是修改为默认的待审核的时候就是请求参数错误
        if (id == null || reviewStatusEnum == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断是否存在
        ServicePicture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 已是该状态
        if (oldPicture.getReviewStatus().equals(reviewStatus)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复审核");
        }
        // 更新审核状态
        ServicePicture updatePicture = new ServicePicture();
        BeanUtils.copyProperties(pictureReviewRequest, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewTime(new Date());
        boolean result = this.updateById(updatePicture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, SystemUser loginUser) {

        // 1. 获取到参数
        String searchText = pictureUploadByBatchRequest.getSearchText();
        Integer count = pictureUploadByBatchRequest.getCount();
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if (StrUtil.isBlank(namePrefix)) {
            namePrefix = searchText;
        }
        // 2. 完整抓取url
        String fetchUrl = String.format(SEARCHBYBATCHWEB, searchText);
        // 3. bing该接口返回的是HTML,解析并提取图片地址
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        }catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"抓取失败，页面获取失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "页面元素获取失败");
        }
        Elements imgElementList = div.select("img.mimg");
        // 4.批量上传图片(也可以批量操作save batch,减少数据库connection创建销毁时间消耗)
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("图片链接为空，已跳过: {}", fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            if (StrUtil.isNotBlank(namePrefix)) {
                // 设置图片名称，序号连续递增
                pictureUploadRequest.setPicName(namePrefix + "_"+ (uploadCount + 1));
            }
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功, id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    @Override
    public Page<PictureVO> listPictureVOByPageWithCache(PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        // 分页参数
        int current = pictureQueryRequest.getCurrent();
        int size = pictureQueryRequest.getPageSize();
        // request参数缓存key
        String queryConditions = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(queryConditions.getBytes());
        // JVM本地缓存key
        String cacheKey = PictureListByPageRedisKeyConstant.PICTURE_BY_PAGE_KEY_SUFFIX_CAFFEINE + hashKey;
        // Redis缓存key
        String redisKey = PictureListByPageRedisKeyConstant.PICTURE_BY_PAGE_KEY_PREFIX_REDIS + hashKey;
        // 1.JVM本地缓存查询
        String cachedValue = LOCAL_CACHE.getIfPresent(cacheKey);
        if (ObjectUtil.isNotNull(cachedValue)) {
            // 如果缓存命中，返回结果
            Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
            return cachedPage;
        }
        // 2.Redis分布式缓存查询
        String redisCachedValue = stringRedisTemplate.opsForValue().get(redisKey);
        if (redisCachedValue != null) {
            // 如果缓存命中，返回结果
            Page<PictureVO> redisCachedPage = JSONUtil.toBean(redisCachedValue, Page.class);
            return redisCachedPage;
        }
        // 3.Mysql数据库查询
        Page<ServicePicture> picturePage = this.page(new Page<>(current, size),
                this.getQueryWrapper(pictureQueryRequest));
        Page<PictureVO> pictureVOPage = this.getPictureVOPage(picturePage, request);  // 获取封装类
        String cacheValue = JSONUtil.toJsonStr(pictureVOPage);  // VO---> JSON
        // 4.存入JVM本地缓存（缓存空值，防止缓存穿透）
        LOCAL_CACHE.put(cacheKey, cacheValue);
        // 5.存入Redis分布式缓存
        stringRedisTemplate.opsForValue().set(redisKey, cacheValue, PictureListByPageRedisKeyConstant.EXPIRE_TIME_REDIS, TimeUnit.SECONDS);
        // 6.异步执行查询次数+1操作
        try {
            PictureQueryTimesThreadPool.pictureQueryTimesRequest(picturePage,this::pictureQueryTimesUpdateBatch);
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return pictureVOPage;
    }


    @Override
    public QueryWrapper<ServicePicture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<ServicePicture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值 generate all getter(auto)
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        // 空间信息
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        // 审核信息
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        // 编辑时间
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        // 从多字段中搜索
        // where (name like "%searchText%" or introduction like "%searchText%") and ...
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            // and() 方法用于将多个条件组合在一起，本身并不会添加 AND 关键字，而是将条件组合在一个括号内，以确保逻辑顺序正确---逻辑分组操作
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "user_id", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "pic_format", picFormat);
        // 只允许用户查看过审的图片
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "review_status", reviewStatus);   // 0
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "review_message", reviewMessage);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewer_id", reviewerId); // 审核人
        // 空间
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "space_id", spaceId);
        queryWrapper.isNull(nullSpaceId, "space_id");
        // others
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "pic_width", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "pic_height", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "pic_size", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "pic_scale", picScale);
        // 某段时间内的编辑过的图片 [)
        queryWrapper.ge(ObjectUtil.isNotNull(startEditTime), "edit_time", startEditTime);
        queryWrapper.lt(ObjectUtil.isNotNull(endEditTime), "edit_time", endEditTime);
        // JSON 数组查询
        // eg：  List<String> tags = Arrays.asList("tag1", "tag2", "tag3");
        //          WHERE tags LIKE '%"tag1"%' AND tags LIKE '%"tag2"%' AND tags LIKE '%"tag3"%'
        // method1:
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        /*
           method2: JSON_QUOTE('tag1')--->"tag1"    $:用于指定 JSON 路径。它表示从 JSON 文档的根元素开始查找
               MySQL 5.7开始提供了 JSON_CONTAINS 函数，可以用来检查一个 JSON 数组中是否包含某个元素
                JSON_QUOTE：将字符串转义为合法的 JSON 字符串格式。它主要用来确保字符串在作为 JSON 值插入或比较时，能够正确地被处理
         */
//        if (CollUtil.isNotEmpty(tags)) {
//            queryWrapper.and(qw -> {
//                for (String tag : tags) {
//                    qw.apply("JSON_CONTAINS(tags, JSON_QUOTE(?), '$')", tag);
//                }
//            });
//        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 单个图片封装：为原有的图片关联创建用户的信息
     */
    @Override
    public PictureVO getPictureVO(ServicePicture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            SystemUser user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 分页获取图片封装
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<ServicePicture> picturePage, HttpServletRequest request) {
        List<ServicePicture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息(避免多次sql-使用 in ids，一次查出所有，避免一个一个sql)
        Set<Long> userIdSet = pictureList.stream().map(ServicePicture::getUserId).collect(Collectors.toSet());
        Map<Long, List<SystemUser>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(SystemUser::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            SystemUser user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }


    @Override
    public void fillReviewParams(ServicePicture picture, SystemUser loginUser) {
        if (userService.isAdmin(loginUser)) {
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());
        } else {
            // 非管理员，创建或编辑都要改为待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    /*
        图片查询次数更新---批量
     */
    public void pictureQueryTimesUpdate(Page<ServicePicture> picturePage) {
        // 构造用于更新的实体类对象列表
        List<ServicePicture> pictureListForBatchUpdate = picturePage.getRecords().stream().map(picture -> {
            return new ServicePicture().setId(picture.getId()).setQueryTimes(picture.getQueryTimes() + 1);
        }).collect(Collectors.toList());
        // 数据库批量更新---自带事务
        boolean result = updateBatchById(pictureListForBatchUpdate);
        if (result) {
            log.info("picture update success");
        }else {
            log.info("picture update fail");
        }
    }

    @Override
    public void checkPictureAuth(SystemUser loginUser, ServicePicture picture) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            // 公共图库，仅本人或管理员可操作
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 私有空间，仅空间管理员可操作
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }


    @Resource
    private SqlSessionFactory sqlSessionFactory;

    /*
        maybe需要改为VO传参，默认只有用户访问的才算是有效queryTime
            其次,需要在getQueryWapper中添加新建字段的排序策略,默认 orderBy QueryTimes降序排列
            其次，update/edit/download的时候更新editTime/downloadTime(表中无此字段,衡量一下需不需要)
     */
    public Long pictureQueryTimesUpdateBatch(Page<ServicePicture> picturePage) {
        // 构造用于更新的实体类对象列表
        List<ServicePicture> pictureListForBatchUpdate = picturePage.getRecords().stream().map(picture -> {
            return new ServicePicture().setId(picture.getId()).setQueryTimes(picture.getQueryTimes() + 1);
        }).collect(Collectors.toList());
        // 数据库批量更新---自带事务
        MybatisBatch<ServicePicture> pictureMybatisBatch = new MybatisBatch<>(sqlSessionFactory, pictureListForBatchUpdate);
        MybatisBatch.Method<ServicePicture> pictureMethod = new MybatisBatch.Method<>(ServicePictureMapper.class);
        // results数组：包含不同操作insert、update的操作结果
        List<BatchResult> results = pictureMybatisBatch.execute(pictureMethod.updateById());
        System.out.println(results.size());
        System.out.println(results.get(0));
        Long successNum = 0L;
        // 每个result中updateCounts()数组：包含特定操作下update中分别更新了n个字段的操作成功与否的数量
        int[] batchResults = results.get(0).getUpdateCounts();
        for (int i = 0; i < batchResults.length; i++) {
            // 应该只有操作1个
            System.out.println(batchResults[i]);
        }
        return 0L;
    }

    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, SystemUser loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        ServiceSpace space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        // 3. 查询该空间下所有图片（必须有主色调）
        List<ServicePicture> pictureList = this.lambdaQuery()
                .eq(ServicePicture::getSpaceId, spaceId)
                .isNotNull(ServicePicture::getPicColor)
                .list();
        // 如果没有图片，直接返回空列表
        if (CollUtil.isEmpty(pictureList)) {
            return Collections.emptyList();
        }
        // 将目标颜色转为 Color 对象
        Color targetColor = Color.decode(picColor);
        // 4. 计算相似度并排序
        List<ServicePicture> sortedPictures = pictureList.stream()
                .sorted(Comparator.comparingDouble(picture -> { // Comparator.comparingDouble() 方法默认按升序排序
                    // 提取图片主色调
                    String hexColor = picture.getPicColor();
                    // 没有主色调的图片放到最后
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color pictureColor = Color.decode(hexColor);
                    // 越大越相似
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                }))
                // 取前 12 个
                .limit(12)
                .collect(Collectors.toList());
        // 转换为 PictureVO
        return sortedPictures.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, SystemUser loginUser) {
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null || CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        ServiceSpace space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        // 已修改权限校验逻辑---团队空间只要是用户有编辑权限即可进行edit
//        if (!loginUser.getId().equals(space.getUserId())) {
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
//        }
        // 3. 查询指定图片，仅选择需要的字段
        List<ServicePicture> pictureList = this.lambdaQuery()
                .select(ServicePicture::getId, ServicePicture::getSpaceId)
                .eq(ServicePicture::getSpaceId, spaceId)
                .in(ServicePicture::getId, pictureIdList)
                .list();

        if (pictureList.isEmpty()) {
            return;
        }
        // 4. 更新分类和标签
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });
        // 批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);
        // 5. 批量更新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, SystemUser loginUser) {
        // 1. 校验图片是否存在
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        // Optional.ofNullable 方法的作用是创建一个可能包含 null 值的 Optional 对象。为空的话就执行orElseThrow
        ServicePicture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 权限校验（这使得不是所有用户都能对public公开图片进行扩图-只有该public图片的创建人/admin可以）
        // 校验权限，已经改为使用注解鉴权
//        checkPictureAuth(loginUser, oldPicture);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

    /**
     * nameRule 格式：图片{序号}
     * Team_Picture_{序号}
     * Team_Picture_1      Team_Picture_2   Team_Picture_3
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<ServicePicture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return;
        }
        long count = 1;
        try {
            for (ServicePicture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }



}
